#include "stdlib.hpp"

#include <purewell/pairfile.hpp>

namespace purewell
{

#define _get_fd(idx) (idx == 0?m_fd:m_fd2)

PWPairFile::PWPairFile() : PWFile(), m_fd2(-1)
{
}

PWPairFile::~PWPairFile(void)
{
	int fd[2];
	detach2(fd);

	if ( -1 != fd[0] )
	{
		::close(fd[0]);
	}

	if ( -1 != fd[1] )
	{
		::close(fd[1]);
	}
}

bool
PWPairFile::attach2(const int fd[2])
{
	m_fd = fd[0];
	m_fd2 = fd[1];
	return true;
}

void
PWPairFile::detach2(int* fd)
{
	if ( fd )
	{
		fd[0] = m_fd;
		fd[1] = m_fd2;
	}

	m_fd = -1;
	m_fd2 = -1;
}

bool
PWPairFile::attach(int fd)
{
	fprintf(stderr,"warning! PWPairFile's using "
		"PWFile::attach is dangerous!\n");
	return PWFile::attach(fd);
}

int
PWPairFile::detach(void)
{
	fprintf(stderr,"warning! PWPairFile's using "
		"PWFile::detach is dangerous!\n");
	return PWFile::detach();
}

void
PWPairFile::destroy(void)
{
	int fd[2];
	detach2(fd);

	if ( -1 != fd[0] ) ::close(fd[0]);
	if ( -1 != fd[1] ) ::close(fd[1]);
}

ssize_t
PWPairFile::read(void* buf, size_t blen, size_t idx)
{
	return ::read(_get_fd(idx), (char*)buf, blen);
}

ssize_t
PWPairFile::write(const void* buf, size_t blen, size_t idx)
{
	return ::write(_get_fd(idx), (const char*)buf, blen);
}

};//namespace purewell

